package com.k8.common.factroy.loader;

import com.k8.common.factroy.instance.InstanceStrategyFactory;
import com.k8.common.util.StrUtil;

import java.util.Collections;
import java.util.List;

public interface ExtensionAccessor {
    ExtensionDirector getExtensionDirector();
    InstanceStrategyFactory getInstanceStrategyFactory();
    default <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
        return getExtensionDirector().getExtensionLoader(type);
    }
    default <T> T getExtension(Class<T> type, String name,boolean registrationRequired) {
        ExtensionLoader<T> extensionLoader = getExtensionLoader(type);
        return extensionLoader != null ? extensionLoader.getExtension(name,registrationRequired) : null;
    }
    default  <T> T getExtension(Class<T> clazz,boolean registrationRequired){
        ExtensionLoader<T> extensionLoader = getExtensionLoader(clazz);
        if (extensionLoader == null) return null;
        String defaultName = extensionLoader.getDefaultName();
        if (StrUtil.isNotEmpty(defaultName)){
            return extensionLoader.getDefaultExtension(registrationRequired);
        }
        return null;
    }
    default <T> T getExtension(Class<T> type, String name) {
        return getExtension(type,name,true);
    }
    default  <T> T getExtension(Class<T> clazz){
        return getExtension(clazz,true);
    }
    default <T> T getAdaptiveExtension(Class<T> type) {
        ExtensionLoader<T> extensionLoader = getExtensionLoader(type);
        return extensionLoader != null ? extensionLoader.getAdaptiveExtension() : null;
    }

    default <T> T getDefaultExtension(Class<T> type) {
        ExtensionLoader<T> extensionLoader = getExtensionLoader(type);
        return extensionLoader != null ? extensionLoader.getDefaultExtension() : null;
    }

    default <T> List<T> getActivateExtensions(Class<T> type) {
        ExtensionLoader<T> extensionLoader = getExtensionLoader(type);
        return extensionLoader != null ? extensionLoader.getActivateExtensions() : Collections.emptyList();
    }

    default <T> T getFirstActivateExtension(Class<T> type) {
        ExtensionLoader<T> extensionLoader = getExtensionLoader(type);
        if (extensionLoader == null) {
            throw new IllegalArgumentException("ExtensionLoader for [" + type + "] is not found");
        }
        List<T> extensions = extensionLoader.getActivateExtensions();
        if (extensions.isEmpty()) {
            throw new IllegalArgumentException("No activate extensions for [" + type + "] found");
        }
        return extensions.get(0);
    }


}
